package bpui.utils;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.plugin.AbstractUIPlugin;

public class RCPUtil {

	private static Map<String, Image> imagesMap;
	private static Map<String, Color> colorMap;
	
	static {
		imagesMap = new HashMap<String, Image>();
		colorMap = new HashMap<String, Color>();
	}
	
	public static void openEditor(String id, IEditorInput input) {
		IWorkbenchWindow window = PlatformUI.getWorkbench()
				.getActiveWorkbenchWindow();
		IWorkbenchPage page = window.getActivePage();
		try {
			page.openEditor(input, id);
		} catch (PartInitException e) {
			throw new RuntimeException(e);
		}
	}

	public static Color getColor(int r, int g, int b) {
		String key = String.format("%d,%d,%d", r, g, b);
		if (!colorMap.containsKey(key)) {
			colorMap.put(key, new Color(Display.getCurrent(), new RGB(r, g, b)));
		}
		return colorMap.get(key);
	}
	
	public static Image getImage(final String pluginName, final String filePath) {
		String key = pluginName + ":" + filePath;
		if (!imagesMap.containsKey(key)) {
			try {
				imagesMap.put(key, AbstractUIPlugin.imageDescriptorFromPlugin(
					pluginName, filePath)
					.createImage());
			} catch (Throwable t) {
				return null;
			}
		}
		return imagesMap.get(key);
	}

	@Override
	protected void finalize() throws Throwable {
		for (String key : imagesMap.keySet()) {
			Image img = imagesMap.get(key);
			if (!img.isDisposed()) {
				img.dispose();
			}
		}
		for (String key : colorMap.keySet()) {
			Color color = colorMap.get(key);
			if (!color.isDisposed()) {
				color.dispose();
			}
		}
		super.finalize();
	}
}